// 生成UUID的简单实现（替代uuid库）
function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

/**
 * 华为云IoT MQTT通信类（浏览器版本）
 * 使用WebSocket连接华为云IoT平台
 */
const HUAWEI_MQTT_CONFIG = {
  // WebSocket代理地址（用于浏览器环境）
  BROKER: 'wss://179c7266d5.st1.iotda-device.cn-north-4.myhuaweicloud.com:8883/mqtt',
  // 设备信息
  DEVICE_ID: '686f5a51d582f2001839e7e1_loT_TEST_001',
  PASSWORD: '2964d3e9b618e4a1015846f527b070c2ae808347ae5b20d2faf64a02d7a96c0b',
  CLIENT_ID: '686f5a51d582f2001839e7e1_loT_TEST_001_0_0_2025071104'
};

class HuaweiIoTMqtt {
  constructor() {
    this.client = null;
    this.requestId = null;
    this.topics = {};
  }

  /**
   * 初始化主题
   */
  initTopics() {
    this.requestId = generateUUID();
    const deviceId = HUAWEI_MQTT_CONFIG.DEVICE_ID;
    this.topics = {
      shadowGetTopic: `$oc/devices/${deviceId}/sys/shadow/get/request_id=${this.requestId}`,
      shadowResponseTopic: `$oc/devices/${deviceId}/sys/shadow/get/response/request_id=${this.requestId}`,
      shadowDeltaTopic: `$oc/devices/${deviceId}/sys/shadow/update/delta`,
      getTopicDown: `$oc/devices/${deviceId}/sys/messages/down`
    };
  }

  /**
   * 连接到MQTT并订阅主题
   */
  connectAndSubscribe(onDataCallback) {
    // 检查是否有可用的MQTT库
    if (typeof window === 'undefined' || !window.mqtt) {
      const error = new Error('MQTT.js库未找到，请确保已正确引入MQTT WebSocket库');
      console.error('[华为云 MQTT]', error.message);
      throw error;
    }
    
    console.log('[华为云 MQTT] 开始连接华为云IoT平台...');
    
    this.initTopics();
    
    const options = {
      clean: true,
      clientId: HUAWEI_MQTT_CONFIG.CLIENT_ID,
      username: HUAWEI_MQTT_CONFIG.DEVICE_ID,
      password: HUAWEI_MQTT_CONFIG.PASSWORD,
      keepalive: 60,
      reconnectPeriod: 1000,
      connectTimeout: 30000 // 30秒超时
    };

    this.client = window.mqtt.connect(HUAWEI_MQTT_CONFIG.BROKER, options);
    this.setupEventListeners(onDataCallback);
  }

  /**
   * 设置MQTT事件监听器
   */
  setupEventListeners(onDataCallback) {
    if (!this.client) return;

    this.client.on('connect', () => {
      console.log('[华为云 MQTT] 连接成功');
      // 订阅主题
      const subscribeTopics = [
        this.topics.shadowGetTopic,
        this.topics.shadowResponseTopic,
        this.topics.shadowDeltaTopic
      ];
      this.client.subscribe(subscribeTopics, { qos: 1 }, (err) => {
        if (!err) {
          console.log('[华为云 MQTT] 订阅成功');
          // 发送shadow get请求
          const requestPayload = JSON.stringify({ object_device_id: HUAWEI_MQTT_CONFIG.DEVICE_ID });
          this.client.publish(this.topics.shadowGetTopic, requestPayload, { qos: 1 });
          console.log('[华为云 MQTT] 已发送上行请求，等待响应...');
        } else {
          console.error('[华为云 MQTT] 订阅失败:', err);
        }
      });
    });

    this.client.on('message', (topic, message) => {
      const msg = message.toString();
      console.log(`[华为云 MQTT] 消息到达 ${topic}: ${msg}`);
      let parsed;
      try {
        parsed = JSON.parse(msg);
        const shadowArray = parsed.shadow;
        if (Array.isArray(shadowArray) && shadowArray.length > 0) {
          const shadowObject = shadowArray[0];
          const serviceId = shadowObject.service_id;
          const reported = shadowObject.reported;
          const reportedProperties = reported.properties;
          const eventTime = reported.event_time;
          const data = {
            serviceId,
            temperature: reportedProperties.temperature,
            illumination: reportedProperties.illumination,
            smoke: reportedProperties.smoke,
            pm25: reportedProperties.pm25,
            eventTime
          };
          if (typeof onDataCallback === 'function') {
            onDataCallback(data);
          }
        }
      } catch (e) {
        console.error('[华为云 MQTT] 解析JSON错误:', e.message);
      }
    });

    this.client.on('close', () => {
      console.log('[华为云 MQTT] 连接丢失，正在重连...');
    });

    this.client.on('error', (err) => {
      console.error('[华为云 MQTT] 连接错误:', err.message);
    });
  }

  /**
   * 断开连接
   */
  disconnect() {
    if (this.client) {
      this.client.end();
      console.log('[华为云 MQTT] 已断开连接');
    }
  }

  /**
   * 检查连接状态
   */
  isConnected() {
    return this.client && this.client.connected;
  }
}

// 导出单例实例
export const huaweiIoTMqtt = new HuaweiIoTMqtt();
export default huaweiIoTMqtt;